import tracker from '../utils/tracker'

export default function injectXHR() {
  let XMLHttpRequest = window.XMLHttpRequest

  let oldOpen = XMLHttpRequest.prototype.open
  let oldSend = XMLHttpRequest.prototype.send

  XMLHttpRequest.prototype.open = function (method, url, async) {
    // 不拦截上报请求
    if (!url.match(/logstores/) && !url.match(/sockjs/)) {
      this.logData = { method, url, async }
    }
    return oldOpen.apply(this, arguments)
  }

  XMLHttpRequest.prototype.send = function (body) {
    if (this.logData) {
      const startTime = Date.now()

      const handler = type => event => {
        let duration = Date.now() - startTime
        let status = this.status
        let statusText = this.statusText

        tracker.send({
          kind: 'stability',
          type: 'xhr',
          eventType: type,
          pathname: this.logData.url,
          status: status + '-' + statusText,
          duration,
          response: this.response ? JSON.stringify(this.response) : '',
          params: body || ''
        })
      }

      this.addEventListener('load', handler('load'))
      this.addEventListener('error', handler('error'))
      this.addEventListener('abort', handler('abort'))
    }
    return oldSend.apply(this, arguments)
  }
}
